﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KZ.Express.H.Settings.Customers;
using KZ.Express.H.Settings.Zones;
using KZ.Express.H.Settings.Users;
using KZ.Express.H.Settings.Suppliers;
using KZ.Express.H.Settings.Carriers;
using KZ.Express.H.Orders;
using KZ.Express.H.Settings.PriceList;
using KZ.Utilities;
using KZ.Express.H.ENT;

namespace KZ.Express.H
{
    public partial class MainView : Form
    {
        #region Fields

        const string _LIST = "ListView", _DETAIL = "DetailView";

        #endregion

        #region Private Methods

        private void MainView_Load(object sender, EventArgs e)
        {
            LoginView view = new LoginView();
            if (view.ShowDialog() == DialogResult.OK)
            {
                foreach (ToolStripMenuItem item in menuStrip1.Items)
                {
                    foreach (ToolStripMenuItem itemdropdown in item.DropDownItems.OfType<ToolStripMenuItem>())
                    {
                        if (UserENT._ROLEID != 1)
                        {
                            if (itemdropdown.Text != "Khách hàng" &&
                                itemdropdown.Text != "Nhà cung cấp" &&
                                itemdropdown.Text != "Dịch vụ" &&
                                itemdropdown.Text != "Đơn hàng" &&
                                itemdropdown.Text != "Đổi mật khẩu"
                                )
                            {
                                itemdropdown.Visible = false;
                            }
                        }
                    }

                    if (UserENT._ROLEID != 1)
                        toolStripSeparator6.Visible = false;
                    if (UserENT._ROLEID == 4)
                    {
                        tsmiStatistical.Visible = true;
                        toolStripSeparator6.Visible = true;
                    }
                }
                ToolbarHandler(String.Empty);
                tsbRefresh.Enabled = tsbCloseTab.Enabled = false;
            }
            else
                Application.Exit();

        }

        private void tbcMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tbcMain.TabPages.Count > 0)
            {
                string tabName = tbcMain.SelectedTab.Name.Split('.').Last();
                BaseView listView = tbcMain.SelectedTab.Controls[tabName + _LIST] as BaseView;
                BaseView detailView = tbcMain.SelectedTab.Controls[tabName + _DETAIL] as BaseView;
                BaseView view = tbcMain.SelectedTab.Controls[tabName] as BaseView;

                if (listView != null && listView.Visible)
                    ToolbarHandler(listView.ActionName);
                else if (detailView != null && detailView.Visible)
                    ToolbarHandler(detailView.ActionName);
                else
                    ToolbarHandler(view.ActionName);
            }
            else
                ToolbarHandler(String.Empty);
        }

        private void CloseTab()
        {
            if (tbcMain.TabPages.Count > 0)
            {
                int index = tbcMain.SelectedIndex;

                foreach (Control ctrl in tbcMain.SelectedTab.Controls)
                    ctrl.Dispose();

                tbcMain.SelectedTab.Dispose();
                tsbRefresh.Enabled = tsbCloseTab.Enabled = tbcMain.TabCount > 0;

                if (index > 0)
                    tbcMain.SelectedIndex = index - 1;
            }
        }

        /// <summary>
        /// enable or disable button on toolbar
        /// </summary>
        /// <param name="actionName"></param>
        private void ToolbarHandler(string actionName)
        {
            tsbInsert.Enabled = false;
            tsbUpdate.Enabled = false;
            tsbDelete.Enabled = false;
            tsbSave.Enabled = false;
            tsbExit.Enabled = false;
            tssImportExport.Visible = false;
            tsbImport.Visible = false;
            tsbExport.Visible = false;
            tsbFuel.Visible = false;
            tsbStandardPrice.Visible = false;

            switch (actionName)
            {
                case "List":
                    tsbInsert.Enabled = true;
                    tsbUpdate.Enabled = true;
                    tsbDelete.Enabled = true;
                    break;

                case "ListWithSave":
                    tsbSave.Enabled = true;
                    tsbDelete.Enabled = true;
                    break;

                case "ListWithSaveExportFuelStandardPrice":
                    tsbSave.Enabled = true;
                    tsbDelete.Enabled = true;
                    tssImportExport.Visible = true;
                    tsbExport.Visible = true;
                    tsbFuel.Visible = true;
                    tsbStandardPrice.Visible = true;
                    break;

                case "ListWithSaveExportFuel":
                    tsbSave.Enabled = true;
                    tsbDelete.Enabled = true;
                    tssImportExport.Visible = true;
                    tsbExport.Visible = true;
                    tsbFuel.Visible = true;
                    break;

                case "ListWithSaveFuelNotDelete":
                    tsbSave.Enabled = true;
                    tsbFuel.Visible = true;
                    break;

                case "Insert":
                case "Update":
                    tsbSave.Enabled = true;
                    tsbExit.Enabled = true;
                    break;
                case "InsertWithImport":
                case "UpdateWithImport":
                    tsbSave.Enabled = true;
                    tsbExit.Enabled = true;
                    tssImportExport.Visible = true;
                    tsbImport.Visible = true;
                    break;

                case "Exit":
                    tsbExit.Enabled = true;
                    break;
            }
        }

        #endregion

        #region Menu

        private void tsmiCustomer_Click(object sender, EventArgs e)
        {
            CustomerListView view = Application.OpenForms["CustomerListView"] as CustomerListView;
            if (view == null)
                view = new CustomerListView();
            OpenTab(view);
        }

        private void tsmiPriceList_Click(object sender, EventArgs e)
        {
            OriginalPriceListView view = Application.OpenForms["OriginalPriceListView"] as OriginalPriceListView;
            if (view == null)
                view = new OriginalPriceListView();
            OpenTab(view);
        }

        private void tsmiZone_Click(object sender, EventArgs e)
        {
            ZoneListView view = Application.OpenForms["ZoneListView"] as ZoneListView;
            if (view == null)
                view = new ZoneListView();
            OpenTab(view);
        }

        private void tsmiUser_Click(object sender, EventArgs e)
        {
            UserListView view = Application.OpenForms["UserListView"] as UserListView;
            if (view == null)
                view = new UserListView();
            OpenTab(view);
        }

        private void tsmiSupplier_Click(object sender, EventArgs e)
        {
            SupplierListView view = Application.OpenForms["SupplierListView"] as SupplierListView;
            if (view == null)
                view = new SupplierListView();
            OpenTab(view);
        }

        private void tsmiCarrier_Click(object sender, EventArgs e)
        {
            CarrierListView view = Application.OpenForms["CarrierListView"] as CarrierListView;
            if (view == null)
                view = new CarrierListView();
            OpenTab(view);
        }

        private void tsmiOrder_Click(object sender, EventArgs e)
        {
            //AdminOrderListView v1 = Application.OpenForms["AdminOrderListView"] as AdminOrderListView;
            //if (v1 == null)
            //    v1 = new AdminOrderListView();
            //OpenTab(v1);
            //SaleOrderListView v2 = Application.OpenForms["SaleOrderListView"] as SaleOrderListView;
            //if (v2 == null)
            //    v2 = new SaleOrderListView();
            //OpenTab(v2);
            //CSOrderListView v3 = Application.OpenForms["CSOrderListView"] as CSOrderListView;
            //if (v3 == null)
            //    v3 = new CSOrderListView();
            //OpenTab(v3);
            //AccountOrderListView v4 = Application.OpenForms["AccountOrderListView"] as AccountOrderListView;
            //if (v4 == null)
            //    v4 = new AccountOrderListView();
            //OpenTab(v4);

            switch (UserENT._ROLEID)
            {
                case 1:
                    AdminOrderListView v1 = Application.OpenForms["AdminOrderListView"] as AdminOrderListView;
                    if (v1 == null)
                        v1 = new AdminOrderListView();
                    OpenTab(v1);
                    break;
                case 2:
                    SaleOrderListView v2 = Application.OpenForms["SaleOrderListView"] as SaleOrderListView;
                    if (v2 == null)
                        v2 = new SaleOrderListView();
                    OpenTab(v2);
                    break;
                case 3:
                    CSOrderListView v3 = Application.OpenForms["CSOrderListView"] as CSOrderListView;
                    if (v3 == null)
                        v3 = new CSOrderListView();
                    OpenTab(v3);
                    break;
                case 4:
                    AccountOrderListView v4 = Application.OpenForms["AccountOrderListView"] as AccountOrderListView;
                    if (v4 == null)
                        v4 = new AccountOrderListView();
                    OpenTab(v4);
                    break;
            }
        }

        private void tsmiStatistical_Click(object sender, EventArgs e)
        {
            StatisticalListView view = Application.OpenForms["StatisticalListView"] as StatisticalListView;
            if (view == null)
                view = new StatisticalListView();
            OpenTab(view);
        }

        private void tsmiLog_Click(object sender, EventArgs e)
        {
            OrderLogListView view = Application.OpenForms["OrderLogListView"] as OrderLogListView;
            if (view == null)
                view = new OrderLogListView();
            OpenTab(view);
        }

        private void tsmiChangePassword_Click(object sender, EventArgs e)
        {
            ChangePasswordView view = new ChangePasswordView();
            view.ShowDialog();
        }

        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            AboutView aboutView = new AboutView();
            aboutView.ShowDialog();
        }

        #endregion

        #region Shortcut

        private void tsmiAddNewRow_Click(object sender, EventArgs e)
        {
            string tabName = tbcMain.SelectedTab.Name.Split('.').Last();
            switch (tabName)
            {
                case "CSOrder":
                    CSOrderListView csOrderView = Application.OpenForms[tabName + _LIST] as CSOrderListView;
                    csOrderView.AddNewRow();
                    break;
                case "AccountOrder":
                    AccountOrderListView accountOrderView = Application.OpenForms[tabName + _LIST] as AccountOrderListView;
                    accountOrderView.AddNewRow();
                    break;
                case "AdminOrder":
                    AdminOrderListView adminOrderView = Application.OpenForms[tabName + _LIST] as AdminOrderListView;
                    adminOrderView.AddNewRow();
                    break;
                default:
                    break;
            }
        }

        private void tsmiInsert_Click(object sender, EventArgs e)
        {
            if (tsbInsert.Enabled)
                ActionHandler("Insert");
        }

        private void tsmiUpdate_Click(object sender, EventArgs e)
        {
            if (tsbUpdate.Enabled)
                ActionHandler("Update");
        }

        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            if (tsbDelete.Enabled)
                ActionHandler("Delete");
        }

        private void tsmiSave_Click(object sender, EventArgs e)
        {
            if (tsbSave.Enabled)
                ActionHandler("Save");
        }

        private void tsmiRefresh_Click(object sender, EventArgs e)
        {
            if (tsbRefresh.Enabled)
                ActionHandler("Refresh");
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            if (tsbExit.Enabled)
                ActionHandler("List");
        }

        private void tsmiImport_Click(object sender, EventArgs e)
        {
            if (tsbImport.Visible)
                ActionHandler("Import");
        }

        private void tsmiExport_Click(object sender, EventArgs e)
        {
            if (tsbExport.Visible)
                ActionHandler("Export");
        }

        private void tsmiFuel_Click(object sender, EventArgs e)
        {
            if (tsbFuel.Visible)
                ActionHandler("UpdateFuel");
        }

        private void tsmiStandardPrice_Click(object sender, EventArgs e)
        {
            if (tsbStandardPrice.Visible)
                ActionHandler("UpdateStandardPrice");
        }

        private void tsmiCloseTab_Click(object sender, EventArgs e)
        {
            if (tsbCloseTab.Enabled)
                CloseTab();
        }

        #endregion

        #region Toolbar

        private void tsbInsert_Click(object sender, EventArgs e)
        {
            ActionHandler("Insert");
        }

        private void tsbUpdate_Click(object sender, EventArgs e)
        {
            ActionHandler("Update");
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            ActionHandler("Delete");
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            ActionHandler("Save");
        }

        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            ActionHandler("Refresh");
        }

        private void tsbExit_Click(object sender, EventArgs e)
        {
            ActionHandler("List");
        }

        private void tsbImport_Click(object sender, EventArgs e)
        {
            ActionHandler("Import");
        }

        private void tsbExport_Click(object sender, EventArgs e)
        {
            ActionHandler("Export");
        }

        private void tsbFuel_Click(object sender, EventArgs e)
        {
            ActionHandler("UpdateFuel");
        }

        private void tsbStandardPrice_Click(object sender, EventArgs e)
        {
            ActionHandler("UpdateStandardPrice");
        }

        private void tsbCloseTab_Click(object sender, EventArgs e)
        {
            CloseTab();
        }

        #endregion

        #region Constructors

        public MainView()
        {
            InitializeComponent();
        }

        #endregion

        #region Public Methods

        public void OpenTab(BaseView view)
        {
            view.Dock = DockStyle.Fill;
            view.TopLevel = false;

            Type type = view.GetType();
            string typeName = type.FullName.Replace(_LIST, String.Empty).Replace(_DETAIL, String.Empty);

            int index;
            if ((index = tbcMain.TabPages.IndexOfKey(typeName)) == -1)
            {
                TabPage tabPage = new TabPage(view.Text);
                tabPage.Name = typeName;
                tabPage.Controls.Add(view);

                tbcMain.TabPages.Add(tabPage);
                index = tbcMain.TabCount - 1;
            }
            else
            {
                if (!tbcMain.TabPages[index].Controls.ContainsKey(view.Name))
                    tbcMain.TabPages[index].Controls.Add(view);
                else
                    view = tbcMain.TabPages[index].Controls[view.Name] as BaseView;
            }

            if (view.Name.EndsWith(_DETAIL))
            {
                BaseView listView = tbcMain.TabPages[index].Controls[view.Name.Replace(_DETAIL, _LIST)] as BaseView;
                listView.Visible = false;
            }
            else if (view.Name.EndsWith(_LIST))
            {
                BaseView detailView = tbcMain.TabPages[index].Controls[view.Name.Replace(_LIST, _DETAIL)] as BaseView;
                if (detailView != null)
                {
                    detailView.Close();
                    detailView.Dispose();
                }
            }

            view.Visible = true;
            tsbRefresh.Enabled = true;
            tsbCloseTab.Enabled = true;

            tbcMain.SelectedIndexChanged += tbcMain_SelectedIndexChanged;
            tbcMain.SelectedIndex = index;
            tbcMain.SelectedIndexChanged -= tbcMain_SelectedIndexChanged;

            ToolbarHandler(view.ActionName);
        }

        /// <summary>
        /// enable or disable button on toolbar
        /// </summary>
        /// <param name="action"></param>
        private void ActionHandler(string action)
        {
            BaseView view, listView, detailView;
            string tabName = tbcMain.SelectedTab.Name;
            switch (action)
            {
                case "Save":
                    tabName = tabName.Split('.').Last();
                    if (tabName == "CSOrder" || tabName == "SaleOrder" || tabName == "AccountOrder" || tabName == "AdminOrder")
                        view = Application.OpenForms[tabName + _LIST] as BaseView;
                    else
                        view = Application.OpenForms[tabName + _DETAIL] as BaseView;
                    view.Save();
                    break;

                case "Delete":
                    tabName = tabName.Split('.').Last();
                    view = Application.OpenForms[tabName + _LIST] as BaseView;
                    view.Delete();
                    break;

                case "Insert":
                    view = Activator.CreateInstance(Type.GetType(tabName + _DETAIL)) as BaseView;
                    if (view != null)
                    {
                        if (tabName.Split('.').Last() == "OriginalPrice")
                            action = "InsertWithImport";

                        view.ActionName = action;
                        OpenTab(view);
                    }
                    break;

                case "Update":
                    view = Activator.CreateInstance(Type.GetType(tabName + _DETAIL)) as BaseView;
                    if (view != null)
                    {
                        tabName = tabName.Split('.').Last();
                        listView = Application.OpenForms[tabName + _LIST] as BaseView;

                        if (tabName.Split('.').Last() == "OriginalPrice")
                            action = "UpdateWithImport";

                        view.ActionName = action;
                        view.EntityID = listView.GetSelected();
                        OpenTab(view);
                    }
                    break;

                case "Import":
                    tabName = tabName.Split('.').Last();
                    listView = tbcMain.SelectedTab.Controls[tabName + _LIST] as BaseView;
                    detailView = tbcMain.SelectedTab.Controls[tabName + _DETAIL] as BaseView;
                    view = tbcMain.SelectedTab.Controls[tabName] as BaseView;

                    if (listView != null && listView.Visible)
                        listView.Import();
                    else if (detailView != null && detailView.Visible)
                        detailView.Import();
                    else
                        view.Import();
                    break;

                case "Export":
                    tabName = tabName.Split('.').Last();
                    listView = tbcMain.SelectedTab.Controls[tabName + _LIST] as BaseView;
                    detailView = tbcMain.SelectedTab.Controls[tabName + _DETAIL] as BaseView;
                    view = tbcMain.SelectedTab.Controls[tabName] as BaseView;

                    if (listView != null && listView.Visible)
                        listView.Export();
                    else if (detailView != null && detailView.Visible)
                        detailView.Export();
                    else
                        view.Export();
                    break;

                case "UpdateFuel":
                    view = Application.OpenForms["SaleOrderListView"] as SaleOrderListView;
                    if (view != null)
                    {
                        (view as SaleOrderListView).UpdateFuel();
                        return;
                    }
                    view = Application.OpenForms["AccountOrderListView"] as AccountOrderListView;
                    if (view != null)
                    {
                        (view as AccountOrderListView).UpdateFuel();
                        return;
                    }
                    view = Application.OpenForms["AdminOrderListView"] as AdminOrderListView;
                    if (view != null)
                    {
                        (view as AdminOrderListView).UpdateFuel();
                        return;
                    }
                    break;

                case "UpdateStandardPrice":
                    view = Application.OpenForms["AdminOrderListView"] as AdminOrderListView;
                    if (view != null)
                    {
                        (view as AdminOrderListView).UpdateStandardPrice();
                        return;
                    }
                    break;

                case "List":
                case "ListWithSave":
                case "ListWithSaveNotDelete":
                    tabName = tabName.Split('.').Last();
                    view = Application.OpenForms[tabName + _LIST] as BaseView;
                    OpenTab(view);
                    break;

                case "Refresh":
                    tabName = tabName.Split('.').Last();
                    listView = tbcMain.SelectedTab.Controls[tabName + _LIST] as BaseView;
                    detailView = tbcMain.SelectedTab.Controls[tabName + _DETAIL] as BaseView;
                    view = tbcMain.SelectedTab.Controls[tabName] as BaseView;

                    if (listView != null && listView.Visible)
                        listView.RefreshData();
                    else if (detailView != null && detailView.Visible)
                        detailView.RefreshData();
                    else
                        view.RefreshData();
                    break;
            }
        }

        #endregion
    }
}
